package com.linxi.wordslog.wordslog

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.linxi.wordslog.Injection
import com.linxi.wordslog.R
import com.linxi.wordslog.adapter.AddAdapter
import com.linxi.wordslog.data.room.Word
import com.linxi.wordslog.wordslogviewmodel.AddWordViewModel
import com.linxi.wordslog.wordslogviewmodel.WordViewModel
import kotlinx.android.synthetic.main.activity_words.*
import kotlinx.android.synthetic.main.fragment_add.*

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [AddFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class AddFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private lateinit var imm: InputMethodManager

    private val wordViewModel by viewModels<WordViewModel> {
        Injection.provideWordViewModelFactory(requireActivity())
    }
    private val addWordViewModel by viewModels<AddWordViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        requireActivity().toolbar.visibility = View.GONE

        return inflater.inflate(R.layout.fragment_add, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        addEditText.requestFocus()
        imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(addEditText, 0)

        val addAdapter = AddAdapter(wordViewModel)
        recyclerviewAdd.apply {
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
            adapter = addAdapter
        }
        addWordViewModel.addWordListLiveData.observe(viewLifecycleOwner, Observer {res->
            if (res != null) {
                addAdapter.submitList(res)
            } else {
                Toast.makeText(activity, "未查询到数据", Toast.LENGTH_SHORT).show()
            }
            progressBar.visibility = View.GONE
        })

        addEditText.addTextChangedListener {
            progressBar.visibility = View.VISIBLE
            val content = it.toString()
            if (content.isNotEmpty()) {
                addWordViewModel.fetchData(content)
            } else {
                addAdapter.submitList(null)
                progressBar.visibility = View.GONE
            }
        }


        buttonCancel.setOnClickListener {
            addEditText.clearFocus()
            findNavController().navigateUp()
        }
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment AddFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            AddFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}